/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from 'react'
import PropTypes from 'prop-types';
import { createAlphabetList } from '../../utils/AToZUtil';
import { filterMembers } from '../../utils/ItemsUtil';
import SectionHeader from './SectionHeader';
import MemberCell from './MemberCell';
import SectionItem from './SectionItem';
import HeaderView from './HeaderView';

import {
	DeviceEventEmitter,
	InteractionManager,
	ListView,
	StyleSheet,
	ScrollView,
	View,
	Dimensions,
	Text
} from 'react-native';

import AlphabetListView from 'react-native-alphabetlistview';

const propTypes = {

}

const EMPTY_SECTION = {'': []}
const alphabetListPaddingTop = 130;

class MemberList extends React.Component {
	constructor(props, context) {
		super(props, context);
		const { memberList } = props;
		this.state = {
			// memberList: EMPTY_SECTION,
      memberAlphabetList: null,
			searchValue: null
		}
		
		this.originalMemberList = props.memberList
		this._mounted = false;
    this.renderHeader = this.renderHeader.bind(this)
    this.triggerChange = this.triggerChange.bind(this)
		this.onChange = this.onChange.bind(this)
	};

	componentDidMount () {
		const { memberList } = this.props;
		this._mounted = true;
		InteractionManager.runAfterInteractions(() => {
			this.setState(this.getStates(memberList));
		});
	};

	componentWillReceiveProps(nextProps) {
		if (this._mounted && this.state.memberList !== nextProps.memberList) {
			this.setState(this.getStates(nextProps.memberList));
    }
	}

	componentWillUnmount () {
		this._mounted = false;
		this.originalMemberList = null;
		this.props.timer && this.clearTimer(this.props.timer);
	}

	onChange (ev) {
		const { memberList } = this.props;
		const match = ev.nativeEvent.text;
		
		this.ev = ev;
    
    if (match) {
      let members = filterMembers(memberList, 'name', match);
			this.updateState(members, match, this.triggerChange);
    } else {
      this.updateState(this.originalMemberList, this.triggerChange);
    }
	};

	triggerChange () {
		if (this.ev && this.ev.nativeEvent) {
			this.props.onChange && this.props.onChange(this.ev)	
		}
	}

	clearTimer = (timer) => {
		cancelAnimationFrame(timer);
		this.props.timer = false;
	}

	updateState (teamMembers, match, callback) {
		if (this._mounted) {
			this.props.timer && this.clearTimer(this.props.timer);
			const timer = requestAnimationFrame(() => {
				this.setState(this.getStates(teamMembers));
				callback && callback()
			})
			this.props.timer = timer;
		}
	};

	getStates (teamMembers) {
		let states = {};
		const memberAlphabetList = createAlphabetList(teamMembers, 'name')
		if (Object.keys(memberAlphabetList).length > 0) {
			states = {memberAlphabetList: memberAlphabetList};
		} else {
			//牛逼的IOS总是可以, 傻逼的安卓，非要我写奇奇怪怪的hack
			states = {memberAlphabetList: EMPTY_SECTION};
		}
		return states
	}
  
  renderHeader () {
		let props = {}
		if (this.state.searchValue) {
			props = Object.assign(props, {defaultValue: this.state.searchValue})
		}
		return (
			<HeaderView
			placeholder='搜索名字'
			onChange={this.onChange}
			renderRow={this.props.renderHeaderContentRow}
      dataSource={this.state.managerDataSource}
      headerContent={this.props.renderHeaderContent}
			{...props}
			/>
		)
	};



	render() {
    const {memberList} = this.props
    const props = this.props;
		return (
      <View style={styles.containerStyle}>
      {this.state.memberAlphabetList && 
        <AlphabetListView 
          initialListSize={1}
          data={this.state.memberAlphabetList}
          cell={MemberCell}
          enableEmptySections={true}
          cellHeight={80}
          stickySectionHeadersEnabled={true}
          sectionListStyle={styles.sectionListStyle}
          sectionListItem={SectionItem}
          renderHeader={this.renderHeader}
          sectionHeader={SectionHeader}
          sectionHeaderHeight={26}
          {...props}
          />
        }
      </View>
		)

  }

}

const styles = StyleSheet.create({
	containerStyle: {
		flex: 1
	},
	contentWrapperStyle : {
		height: 100
	},
	sectionListStyle: {
		flexDirection: 'column',
		alignItems: 'center',
		paddingLeft: 10,	
		paddingRight: 4,	
		paddingTop: alphabetListPaddingTop
	}
});

MemberList.propTypes = propTypes;

export default MemberList;